import { uid } from 'quasar';
import { defineStore } from 'pinia';
import { deepCopy } from '../util/utils';
import {
  CPageNode,
  CComponentStateItem,
  CPoint, CProjectNode,
  EnumEditorEvent, EPageType,
  CGraphEntity, CSelectGraph
} from './editorModels';
import { searchMax, searchMin } from 'src/hook/common/useUitil';


export const useEditorStore = defineStore('canvas', {
  state: () => {
    return {
      project: <CProjectNode>{
        id: 0,
        cname: '',
        companyId: 0,
        wsAddr: '',
        wsPort: 0,
        sortCode: '',
        description: ''
      },
      pageType: EPageType.NULL_PAGE,  //0代表模板，1代表已建立页面
      canvas: <CPageNode>{
        id: 0,
        cname: '',
        backgroundColor: 'white',
        backgroundImage: null,
        resolution: '16:9',
        width: 800, //修正画布尺寸
        height: 600,
        wsAddr: '',
        wsPort: 0,
        projectId: 0,
        sortCode: '',
        description: ''
      },
      selectedIsCanvas: true,
      components: <CGraphEntity[]>[],
      componentState: <CComponentStateItem[]>[],
      selectedComponent: null as CSelectGraph,  // 存当前选择对象，若是多选则此为空
      selectedList: [] as string[],    //存储选择项comSid,string[]

      deletedList: [] as number[],    //存储要删除组件id,number[]
      copiedList: [] as string[],    //存储要复制组件comSid,string[]
      pasteCount: 0,                   //单个组件粘贴最大次数为5次
      moveComponent: {                //记录移动组件初始位置
        point: { x: 0, y: 0 },
        comSid: ''
      }
    }
  },

  getters: {

  },

  actions: {
    //初始化project
    initProject () {
      this.project.id = 0;
      this.project.cname = '';
    },

    //初始化页面类型0位模板，1为普通页面
    initPageType () {
      this.pageType = EPageType.NULL_PAGE;
    },

    //初始化canvas
    initCanvas (): void {
      this.canvas.id = 0;
      this.canvas.cname = '';
      this.canvas.backgroundColor = 'white';
      this.canvas.backgroundImage = null;
      this.canvas.resolution = '16:9';
      this.canvas.width = 800; //修正画布尺寸
      this.canvas.height = 600;
      this.canvas.wsAddr = '';
      this.canvas.wsPort = 0;
    },


    //初始化组件管理
    initComponents (): void {
      this.selectedIsCanvas = true;
      this.components.length = 0;
      this.componentState.length = 0;
      this.selectedComponent = null;
      this.selectedList.length = 0;
      this.copiedList.length = 0;
      this.deletedList.length = 0;
    },


    //删除列表
    initDeletedList (): void {
      this.deletedList.length = 0;
    },

    //设置project
    setProject (id: number, name: string) {
      this.project.id = id;
      this.project.cname = name;
    },

    //设置页面类型
    setPage (nType: EPageType, id: number) {
      this.pageType = nType;
      this.canvas.id = id;
    },

    // 画布属性设置
    setCanvas (ca: CPageNode): void {
      this.canvas.id = ca.id;
      this.canvas.typeId = ca.typeId;
      this.canvas.imgUrl = ca.imgUrl;
      this.canvas.cname = ca.cname;
      this.canvas.backgroundColor = ca.backgroundColor;
      this.canvas.backgroundImage = ca.backgroundImage;
      this.canvas.resolution = ca.resolution;
      this.canvas.width = ca.width;
      this.canvas.height = ca.height;
      this.canvas.wsAddr = ca.wsAddr;
      this.canvas.wsPort = ca.wsPort;
    },

    // 当前鼠标停留在画布操作
    setCanvasSelected (selected: boolean): void {
      this.selectedIsCanvas = selected;
    },

    //新生成组件,加入页面组件列表，选中状态
    addComponents (component: CGraphEntity): void {
      let index = this.components.findIndex((item) => (item.comSid === component.comSid));
      if (index === -1) {
        //新建初始状态为选中状态
        let state: CComponentStateItem = {
          comSid: component.comSid,
          selected: false
        }

        //组件列表、管理列表同步
        this.components.push(component);
        this.componentState.push(state);
      }
    },

    // 新增加组件选择表，将组件列表状态置成“选中状态”
    addSelectedComponent (comSid: string): void {
      let index = this.componentState.findIndex((item) => (item.comSid === comSid))
      if (index !== -1) {
        this.componentState[index].selected = true;

        //选择项列表
        if (this.selectedList.indexOf(comSid) === -1) {
          this.selectedList.push(comSid);
        }
      }

      //判断选中组件数量,若为1则写入到selectedComponent,否则清空
      if (this.selectedList.length === 1) {
        let index = this.componentState.findIndex((item) => (item.selected === true));
        if (index !== -1) {
          this.selectedComponent = this.components[index];
        }
      } else {
        this.selectedComponent = null;
      }
    },

    //从选择控件列表删除1个组件
    removeSelectedComponent (comSid: string): void {
      let index = this.componentState.findIndex((item) => (item.comSid === comSid));
      if (index !== -1) {
        this.componentState[index].selected = false;
        let k = this.selectedList.indexOf(comSid);
        if (k !== -1) {
          this.selectedList.splice(k, 1);
        }
      }

      if (this.selectedComponent?.comSid === comSid) {
        this.selectedComponent = null;
      }

      //判断选中组件数量,若为1则写入到selectedComponent,否则清空
      if (this.selectedList.length === 1) {
        let index = this.componentState.findIndex((item) => (item.selected === true));
        if (index !== -1) {
          this.selectedComponent = this.components[index];
        }
      } else {
        this.selectedComponent = null;
      }
    },

    //全选
    addAllSelectedComponents (): void {
      for (let i = 0; i < this.componentState.length; i++) {
        this.componentState[i].selected = true;
        this.selectedList[i] = this.componentState[i].comSid;
      }

      //判断选中组件数量,若为1则写入到selectedComponent,否则清空
      if (this.selectedList.length === 1) {
        let index = this.componentState.findIndex((item) => (item.selected === true));
        if (index !== -1) {
          this.selectedComponent = this.components[index];
        }
      } else {
        this.selectedComponent = null;
      }
    },

    //清空选择组件列表
    clearAllSelectedComponents (): void {
      for (let i = 0; i < this.componentState.length; i++) {
        this.componentState[i].selected = false;
      }

      //选择列表清空
      this.selectedList.length = 0;
      this.selectedComponent = null;
    },

    //判断是否被中选
    isHasSelectedComponent (comSid: string):boolean {
      let index = this.selectedList.indexOf(comSid);
      return (index === -1) ? false : true;
    },

    //删除组件
    deleteComponents (): void {
      if (this.selectedList.length > 0) {
        for (let i = 0; i < this.componentState.length; i++) {
          if (this.componentState[i].selected === true) {
            let id = this.components[i].id;
            this.components.splice(i, 1);
            this.componentState.splice(i, 1);
            if (id > 0) {
              this.deletedList.push(id);
            }
          }
        }
      }
    },

    //复制选中组件,保存comSid
    setCopySrcComponents (): void {
      this.copiedList.length = 0;
      this.pasteCount = 0;
      for (let i = 0; i < this.selectedList.length; i++) {
        this.copiedList.push(this.selectedList[i]);
      }
    },

    //粘贴组件
    pasteComponents (): void {
      for (let i = 0; i < this.copiedList.length; i++) {
        let comSid = this.copiedList[i];
        let index = this.components.findIndex((item) => (item.comSid === comSid));
        if (index !== -1) {
          //console.log('paste:' + comSid);
          let component = deepCopy(this.components[index]);
          component.comSid = uid();
          component.position.x += 50;
          component.position.y += 50;
          this.addComponents(component);
          this.pasteCount++;
        }
      }
    },

    //取消
    cancelComponents (): void {
      this.copiedList.length = 0;
      this.selectedList.length = 0;
      this.selectedComponent = null;
      this.componentState.forEach((item) => {
        item.selected = false;
      });
    },

    //组件移动时记录初始位置
    initSelectedComponentPosition (point: CPoint, comSid: string) {
      this.moveComponent.point.x = point.x;
      this.moveComponent.point.y = point.y;
      this.moveComponent.comSid = comSid;
    },

    //移动过程中位置变化
    moveSelectedComponentPosition () {
      //console.log('EDITOR_MOUSE_EVT_MOVE');
      this.execute(EnumEditorEvent.EDITOR_MOUSE_EVT_MOVE);
    },

    //执行编辑命令
    execute (evt: EnumEditorEvent): void {
      let arr: number[] = [];
      let min = 0;
      let max = 0;
      switch (evt) {
        case EnumEditorEvent.EDITOR_KEY_EVT_COPY:
          if (this.selectedList.length > 0) {
            this.setCopySrcComponents();
          }
          break;
        case EnumEditorEvent.EDITOR_KEY_EVT_PASTE:
          if (this.copiedList.length > 0) {
            this.pasteComponents();
          }
          break;

        case EnumEditorEvent.EDITOR_KEY_EVT_DEL:
          if (this.selectedList.length > 0) {
            this.deleteComponents();
          }
          break;
        case EnumEditorEvent.EDITOR_KEY_EVT_ESC:
          this.cancelComponents();  //取消复制内容
          break;

        case EnumEditorEvent.EDITOR_KEY_EVT_LEFT_MOVE:
          if (this.selectedList.length > 0) {
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.x -= 5;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_KEY_EVT_RIGHT_MOVE:
          if (this.selectedList.length > 0) {
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.x += 5;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_KEY_EVT_UP_MOVE:
          if (this.selectedList.length > 0) {
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.y -= 5;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_KEY_EVT_DOWN_MOVE:
          if (this.selectedList.length > 0) {
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.y += 5;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_POSITIVE_ROTATE:
          if (this.selectedList.length > 0) {
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].shape.transform += 90;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_NEGATIVE_ROTATE:
          if (this.selectedList.length > 0) {
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].shape.transform -= 90;
              }
            }
          }
          break;

        case EnumEditorEvent.EDITOR_BTN_EVT_TOP_ALIGN:
          if (this.selectedList.length > 0) {
            arr.length = 0;
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let xy = this.components[i].position.y
                arr.push(xy);
              }
            }
            //查找最最小坐标值
            min = searchMin(arr);
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.y = min;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_BOTTOM_ALIGN:
          if (this.selectedList.length > 0) {
            arr.length = 0;
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let xy = this.components[i].position.y + this.components[i].position.y;
                arr.push(xy);
              }
            }
            //查找最最小坐标值
            max = searchMax(arr);
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.y = max;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_VR_CENTER_ALIGN:
          if (this.selectedList.length > 0) {
            arr.length = 0;
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let xy = this.components[i].position.y + this.components[i].position.h / 2;
                arr.push(xy);
              }
            }
            //查找最最小坐标值
            max = searchMax(arr);
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let cx = this.components[i].position.y + this.components[i].position.h / 2;
                let dx = cx - max;
                this.components[i].position.y += cx;
              }
            }
          }
          break;

        case EnumEditorEvent.EDITOR_BTN_EVT_LEFT_ALIGN:
          if (this.selectedList.length > 0) {
            arr.length = 0;
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let xy = this.components[i].position.x
                arr.push(xy);
              }
            }
            //查找最最小坐标值
            min = searchMin(arr);
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.x = min;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_RIGHT_ALIGN:
          if (this.selectedList.length > 0) {
            arr.length = 0;
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let xy = this.components[i].position.x + this.components[i].position.w;
                arr.push(xy);
              }
            }
            //查找最最小坐标值
            max = searchMax(arr);
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                this.components[i].position.x = max;
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_HR_CENTER_ALIGN:
          if (this.selectedList.length > 0) {
            arr.length = 0;
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let xy = this.components[i].position.x + this.components[i].position.w / 2;
                arr.push(xy);
              }
            }
            //查找最最小坐标值
            max = searchMax(arr);
            for (let i = 0; i < this.componentState.length; i++) {
              if (this.componentState[i].selected === true) {
                let cx = this.components[i].position.x + this.components[i].position.w / 2;
                let dx = cx - max;
                this.components[i].position.x += cx;
              }
            }
          }
          break;

        case EnumEditorEvent.EDITOR_MOUSE_EVT_MOVE:
          if (this.selectedList.length > 0) {
            let dx = 0, dy = 0;
            //console.log('Mouse move:' + this.moveComponent.comSid);
            let index = this.componentState.findIndex((item) => (item.comSid === this.moveComponent.comSid));
            if (index !== -1) {
              dx = this.components[index].position.x - this.moveComponent.point.x;
              dy = this.components[index].position.y - this.moveComponent.point.y;
              this.moveComponent.point.x = this.components[index].position.x;
              this.moveComponent.point.y = this.components[index].position.y;

              //console.log('dx:' + dx + '----' + 'dy:' + dy);
              for (let i = 0; i < this.components.length; i++) {
                if ((this.componentState[i].selected === true) && (i !== index)) {
                  this.components[i].position.x += dx;
                  this.components[i].position.y += dy;
                }
              }
            }
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_TOP_LAYER:
          for (let i = 0; i < this.components.length; i++) {
            arr.push(this.components[i].shape.zIndex);
          }

          //查找最最小坐标值
          max = searchMax(arr);

          //每个组件zIndex-1
          for (let i = 0; i < this.components.length; i++) {
            this.components[i].shape.zIndex -= 1;
          }

          //选中组件设置最大
          if (this.selectedComponent) {
            this.selectedComponent.shape.zIndex = max;
          }
          break;
        case EnumEditorEvent.EDITOR_BTN_EVT_BOTTOM_LAYER:
          for (let i = 0; i < this.components.length; i++) {
            arr.push(this.components[i].shape.zIndex);
          }

          //查找最最小坐标值
          min = searchMin(arr);

          //每个组件zIndex-1
          for (let i = 0; i < this.components.length; i++) {
            this.components[i].shape.zIndex += 1;
          }

          //选中组件设置最大
          if (this.selectedComponent) {
            this.selectedComponent.shape.zIndex = min;
          }
          break;
        default:
          console.warn('不支持的命令.');
          break;
      }
    }
  },

  undo: {   //undo redo
    omit: ['selectedIsCanvas']  // 忽略该变量
  }
});
